package cn.wps.solution.demo.service;

import cn.wps.solution.demo.entity.File;
import cn.wps.solution.demo.entity.User;
import cn.wps.solution.demo.repository.FileRepository;
import cn.wps.solution.demo.repository.StorageRepository;
import cn.wps.solution.weboffice.provider.v3.exception.FileNotExist;
import cn.wps.solution.weboffice.provider.v3.model.FileInfo;
import cn.wps.solution.weboffice.provider.v3.model.FileUploadSinglePhase;
import cn.wps.solution.weboffice.provider.v3.service.SinglePhaseFileStorageService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class SinglePhaseFileStorageServiceImpl implements SinglePhaseFileStorageService {
    @Autowired
    private FileRepository fileRepository;

    @Autowired
    private StorageRepository storageRepository;

    @Autowired
    private PreviewServiceImpl previewService;

    @Override
    @SneakyThrows
    public FileInfo uploadFile(FileUploadSinglePhase.Request request) {
        final User user = previewService.fetchUserByToken();

        final File file = Optional.ofNullable(request)
                .map(r -> previewService.fetchFile(request.getFileId()))
                .map(f -> File.builder()
                        .id(f.getId().copyForNewVersion())
                        .creator(f.getCreator())
                        .createTime(f.getCreateTime())
                        .modifyTime(LocalDateTime.now())
                        .modifier(user)
                        .name(request.getName())
                        .size(request.getSize())
                        .build())
                .map(f -> fileRepository.save(f))
                .orElseThrow(FileNotExist::new);

        this.storageRepository.save(file.getId(), request.getFile().getBytes());

        return file.toFileInfo();
    }
}
